package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    static ThreadPoolExecutor threadPoolExecutor;

    static {
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {


        loadServer(threadPoolExecutor);


    }

    private List<Service> services = new ArrayList<>();

    /**
     * 加载server
     *
     * @param threadPoolExecutor
     */
    private void loadServer(ThreadPoolExecutor threadPoolExecutor) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//service");

            selectNodes.forEach(element -> {
                Service service = new Service();
                services.add(service);
                Connector connector = new Connector();
                service.setConnector(connector);
                Engine engine = new Engine();
                service.setEngine(engine);

                // 设置connector
                Element connectorElement = (Element) element.selectSingleNode("connector");
                String port = connectorElement.attribute("port").getValue();
                connector.setPort(Integer.valueOf(port));

                // 设置engine
                Element engineElement = (Element) element.selectSingleNode("engine");
                Host host = new Host();
                engine.setHosts(List.of(host));

                // 设置host
                Element hostElement = (Element) engineElement.selectSingleNode("host");
                String appBase = hostElement.attribute("appBase").getStringValue();
                String name = hostElement.attribute("name").getStringValue();
                host.setAppBase(appBase);
                host.setName(name);

                try {
                    service.init(threadPoolExecutor);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
